package com.semidata.trp.algorithm.request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.CharsetUtil;

import com.semidata.rtd.core.http.server.HttpSession;
import com.semidata.rtd.core.json.JsonArray;
import com.semidata.rtd.core.json.JsonObject;
import com.semidata.rtd.core.log.Logger;
import com.semidata.rtd.engine.job.Job;
import com.semidata.rtd.engine.job.SyncTask;
import com.semidata.trp.algorithm.job.AlgorithmJob;
import com.semidata.trp.algorithm.job.AlgorithmJobContext;

public class TaskRequest extends SyncTask{

	public TaskRequest(Job job) {
		super(job, 0);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run() throws Exception {
		// TODO Auto-generated method stub
		AlgorithmJobContext context = ((AlgorithmJob)getJob()).getJobContext(); 
		HttpSession session = context.getHttpSession();
        StrategyContext strategyContext = new StrategyContext();
        try {
        	String args = session.getBody(CharsetUtil.UTF_8);
        	if (args == null || args.length() == 0)
        		throw new Exception("post content is null");
        	System.out.println(args);
        	JsonObject arguments = new JsonObject(args);
        	if (arguments.containsField("position_id")){
        		String positionId = arguments.getString("position_id");
        		if (positionId != null && positionId.length() > 0)
        			strategyContext.setPositionId(Integer.parseInt(positionId));
        	}
        	if (arguments.containsField("media_type")){
        		String mediaType = arguments.getString("media_type");
        		if (mediaType != null && mediaType.length() > 0)
        			strategyContext.setMediaType(Integer.parseInt(mediaType));
        	}
        	if (arguments.containsField("position_max")){
        		String positionMax = arguments.getString("position_max");
        		if (positionMax != null && positionMax.length() > 0)
        			strategyContext.setPositionColumns(Integer.parseInt(positionMax));
        	}
        	if (arguments.containsField("areas")){
        		String areaCode = arguments.getString("areas");
        		if (areaCode != null && areaCode.length() > 0)
        			strategyContext.setAreaCode(areaCode);
        	}
        	if (arguments.containsField("words")){
        		String words = arguments.getString("words");
        		if (words != null && words.length() > 0) {
        			String []keywords = words.split(":");
        			StringBuffer keyword1 = new StringBuffer();
        			StringBuffer keyword2 = new StringBuffer();
        			StringBuffer keyword3 = new StringBuffer();
        			int keyLength = keywords.length;
        			if (keyLength > 0)
        				keyword1.append(keywords[0]);
        			if (keyLength > 1)
        				keyword2.append(keywords[1]);
        			if (keyLength > 2)
        				keyword3.append(keywords[2]);
        			strategyContext.setRequestKeyWord1(keyword1.toString());
        			strategyContext.setRequestKeyWord2(keyword2.toString());
        			strategyContext.setRequestKeyWord3(keyword3.toString());
        		}
        	}
        	if (arguments.containsField("material")){
        		if (arguments.getElement("material").isArray()) {
        			JsonArray frequencies = arguments.getArray("material");
        			Map<String,Integer> frequency = new HashMap<>();
        			for (int i = 0; i <frequencies.size(); i++) {
        				JsonObject fre = frequencies.get(i);
        				if (fre.containsField("id") && fre.containsField("max")) {
        					String id = fre.getString("id");
        					String max = fre.getString("max");
        					if (id != null && id.length() > 0 && max != null && max.length() > 0)
        						frequency.put(fre.getString("id"), Integer.parseInt(fre.getString("max")));
        				}
        			}
        			strategyContext.setMaterialFrequency(frequency);
        		}
        	}
        	
        	if (arguments.containsField("validmaterials")) {
        		if (arguments.getElement("validmaterials").isArray()) {
        			JsonArray materials = arguments.getArray("validmaterials");
        			List<String> ids = new ArrayList<String>();
        			for(int i = 0; i<materials.size(); i++) {
        				String id = materials.get(i);
        				ids.add(id) ;
        				System.out.println(id.toString());
        			}
        			strategyContext.setMaterialsId(ids);
        		}
        	}
        	
        	
        	if (arguments.containsField("org")){
        		if(arguments.getElement("org").isObject()) {
        			JsonObject orgCost = arguments.getObject("org");
        			if (orgCost.containsField("dailyCostIn")) {
        				String dailyCostIn = orgCost.getString("dailyCostIn");
        				if (dailyCostIn != null && dailyCostIn.length() > 0)
        					strategyContext.setOrgTodayInternalCost(Double.parseDouble(dailyCostIn));
        			}
        			if (orgCost.containsField("dailyCostOut")) {
        				String dailyCostOut = orgCost.getString("dailyCostOut");
        				if (dailyCostOut != null && dailyCostOut.length() > 0)
        					strategyContext.setOrgTodayExternalCost(Double.parseDouble(dailyCostOut));
        			}
        			if (orgCost.containsField("dailyCostAlly")) {
        				String dailyCostAlly = orgCost.getString("dailyCostAlly");
        				if (dailyCostAlly != null && dailyCostAlly.length() > 0)
        					strategyContext.setOrgTodayAllyCost(Double.parseDouble(dailyCostAlly));
        			}
        			if (orgCost.containsField("totalCostIn")) {
        				String totalCostIn = orgCost.getString("totalCostIn");
        				if (totalCostIn != null && totalCostIn.length() > 0)
        					strategyContext.setOrgTotalInternalCost(Double.parseDouble(totalCostIn));
        			}
        			if (orgCost.containsField("totalCostOut")) {
        				String totalCostOut = orgCost.getString("totalCostOut");
        				if (totalCostOut != null && totalCostOut.length() > 0)
        					strategyContext.setOrgTotalExternalCost(Double.parseDouble(totalCostOut));
        			}
        			if (orgCost.containsField("totalCostAlly")) {
        				String totalCostAlly = orgCost.getString("totalCostAlly");
        				if (totalCostAlly != null && totalCostAlly.length() > 0)
        					strategyContext.setOrgTotalAllyCost(Double.parseDouble(totalCostAlly));
        			}
        		}
        		
        	}
        	if (arguments.containsField("resource")) {
        		if(arguments.getElement("resource").isObject()) {
        			JsonObject resource = arguments.getObject("resource");
        			if (resource.containsField("dailyPv")) {
        				String dailyPv = resource.getString("dailyPv");
        				if (dailyPv != null && dailyPv.length() > 0)
        					strategyContext.setResourceTodayImpression(Long.parseLong(dailyPv));
        			}
        			if (resource.containsField("dailyClick")) {
        				String dailyClick= resource.getString("dailyClick");
        				if (dailyClick != null && dailyClick.length() > 0)
        					strategyContext.setResourceTodayClick(Long.parseLong(dailyClick));
        			}

        			if (resource.containsField("totalPv")) {
        				String totalPv = resource.getString("totalPv");
        				if (totalPv != null && totalPv.length() > 0)
        					strategyContext.setResourceTotalImpression(Long.parseLong(totalPv));
        			}

        			if (resource.containsField("totalClick")) {
        				String totalClick= resource.getString("totalClick");
        				if (totalClick != null && totalClick.length() > 0)
        					strategyContext.setResourceTotalClick(Long.parseLong(totalClick));
        			}
        		}
        	}
        	if (arguments.containsField("strategy")) {
        		if (arguments.getElement("strategy").isObject()) {
        			JsonObject strategy = arguments.getObject("strategy");
        			if (strategy.containsField("dailyCostIn")) {
        				String dailyCostIn = strategy.getString("dailyCostIn");
        				if (dailyCostIn != null && dailyCostIn.length() > 0) {
        					strategyContext.setStrategyTodayInternalCost(Double.parseDouble(dailyCostIn));
        				}
        			}
        			if (strategy.containsField("dailyCostOut")) {
        				String dailyCostOut = strategy.getString("dailyCostOut");
        				if (dailyCostOut != null && dailyCostOut.length() > 0) {
        					strategyContext.setStrategyTodayExternalCost(Double.parseDouble(dailyCostOut));
        				}
        			}
        			if (strategy.containsField("dailyCostAlly")) {
        				String dailyCostAlly = strategy.getString("dailyCostAlly");
        				if (dailyCostAlly != null && dailyCostAlly.length() > 0) {
        					strategyContext.setStrategyTodayAllyCost(Double.parseDouble(dailyCostAlly));
        				}
        			}
        			if (strategy.containsField("totalCostIn")) {
        				String totalCostIn = strategy.getString("totalCostIn");
        				if (totalCostIn != null && totalCostIn.length() > 0) {
        					strategyContext.setStrategyTotalInternalCost(Double.parseDouble(totalCostIn));
        				}
        			}
        			if (strategy.containsField("totalCostOut")) {
        				String totalCostOut = strategy.getString("totalCostOut");
        				if (totalCostOut != null && totalCostOut.length() > 0) {
        					strategyContext.setStrategyTotalExternalCost(Double.parseDouble(totalCostOut));
        				}
        			}
        			if (strategy.containsField("totalCostAlly")) {
        				String totalCostAlly = strategy.getString("totalCostAlly");
        				if (totalCostAlly != null && totalCostAlly.length() > 0) {
        					strategyContext.setStrategyTotalAllyCost(Double.parseDouble(totalCostAlly));
        				}
        			}
        			if (strategy.containsField("dailyPvIn")) {
        				String dailyPvIn = strategy.getString("dailyPvIn");
        				if (dailyPvIn != null && dailyPvIn.length() > 0) {
        					strategyContext.setStrategyTodayInternalImpression(Long.parseLong(dailyPvIn));
        				}
        			}
        			if (strategy.containsField("dailyPvOut")) {
        				String dailyPvOut = strategy.getString("dailyPvOut");
        				if (dailyPvOut != null && dailyPvOut.length() > 0) {
        					strategyContext.setStrategyTodayExternalImpression(Long.parseLong(dailyPvOut));
        				}
        			}
        			if (strategy.containsField("dailyPvAlly")) {
        				String dailyPvAlly = strategy.getString("dailyPvAlly");
        				if (dailyPvAlly != null && dailyPvAlly.length() > 0) {
        					strategyContext.setStrategyTodayAllyImpression(Long.parseLong(dailyPvAlly));
        				}
        			}
        			if (strategy.containsField("totalPvIn")) {
        				String totalPvIn = strategy.getString("totalPvIn");
        				if (totalPvIn != null && totalPvIn.length() > 0) {
        					strategyContext.setStrategyTotalInternalImpression(Long.parseLong(totalPvIn));
        				}
        			}
        			if (strategy.containsField("totalPvOut")) {
        				String totalPvOut = strategy.getString("totalPvOut");
        				if (totalPvOut != null && totalPvOut.length() > 0) {
        					strategyContext.setStrategyTotalExternalImpression(Long.parseLong(totalPvOut));
        				}
        			}
        			if (strategy.containsField("totalPvAlly")) {
        				String totalPvAlly = strategy.getString("totalPvAlly");
        				if (totalPvAlly != null && totalPvAlly.length() > 0) {
        					strategyContext.setStrategyTotalAllyImpression(Long.parseLong(totalPvAlly));
        				}
        			}
        			if (strategy.containsField("dailyClick")) {
        				String dailyClick = strategy.getString("dailyClick");
        				if (dailyClick != null && dailyClick.length() > 0) {
        					strategyContext.setStrategyTodayClick(Long.parseLong(dailyClick));
        				}
        			}
        			if (strategy.containsField("totalClick")) {
        				String totalClick = strategy.getString("totalClick");
        				if (totalClick != null && totalClick.length() > 0) {
        					strategyContext.setStrategyTotalClick(Long.parseLong(totalClick));
        				}
        			}
        			if (strategy.containsField("dailyBudgetIn")) {
        				String dailyBudgetIn = strategy.getString("dailyBudgetIn");
        				if (dailyBudgetIn != null && dailyBudgetIn.length() > 0) {
        					strategyContext.setDailyBudgetIn(Double.parseDouble(dailyBudgetIn));
        				}
        			}
        			if (strategy.containsField("dailyBudgetOut")) {
        				String dailyBudgetOut = strategy.getString("dailyBudgetOut");
        				if (dailyBudgetOut != null && dailyBudgetOut.length() > 0) {
        					strategyContext.setDailyBudgetOut(Double.parseDouble(dailyBudgetOut));
        				}
        			}
        			if (strategy.containsField("dailyBudgetAlly")) {
        				String dailyBudgetAlly = strategy.getString("dailyBudgetAlly");
        				if (dailyBudgetAlly!= null && dailyBudgetAlly.length() > 0) {
        					strategyContext.setDailyBudgetAlly(Double.parseDouble(dailyBudgetAlly));
        				}
        			}
        			if (strategy.containsField("totalBudgetIn")) {
        				String totalBudgetIn = strategy.getString("totalBudgetIn");
        				if (totalBudgetIn != null && totalBudgetIn.length() > 0) {
        					strategyContext.setTotalBudgetIn(Double.parseDouble(totalBudgetIn));
        				}
        			}
        			if (strategy.containsField("totalBudgetOut")) {
        				String totalBudgetOut = strategy.getString("totalBudgetOut");
        				if (totalBudgetOut != null && totalBudgetOut.length() > 0) {
        					strategyContext.setTotalBudgetOut(Double.parseDouble(totalBudgetOut));
        				}
        			}
        			if (strategy.containsField("totalBudgetAlly")) {
        				String totalBudgetAlly = strategy.getString("totalBudgetAlly");
        				if (totalBudgetAlly != null && totalBudgetAlly.length() > 0) {
        					strategyContext.setTotalBudgetAlly(Double.parseDouble(totalBudgetAlly));
        				}
        			}
        		}
        	}
        	if (arguments.containsField("xml")) {
        		if (arguments.getElement("xml").isObject()){
        			strategyContext.setParams(arguments.getObject("xml"));
        		}
        	}
        	if (arguments.containsField("code")) {
        		String code = arguments.getString("code");
        		if (code != null && code.length() > 0) {
        			context.setCode(code.toString());
        		} else
        			throw new Exception("No code content error");
        	} else {
        		throw new Exception("No code argument");
        	}
        } catch (Exception e) {
        	Logger.log("ERROR", "request error : " + e);
        	e.printStackTrace();
        	throw e;
        }
        context.setArgs(strategyContext);
        
	}

}
